#include "OneLineUltrasonic.h"
#include "Arduino.h"


OneLineUltrasonic::OneLineUltrasonic( uint8_t port)
{
	      _oneLineUltrasonic_pin = port;
	    
  _lastEnterTime = millis();
  _measureFlag = true;
  _measureValue = 0;
}

long OneLineUltrasonic::measure(unsigned long timeout)
{
  long duration;
  
  if(millis() - _lastEnterTime > 23)
  {
    _measureFlag = true; 
  }

  if(_measureFlag == true)
  {
    _lastEnterTime = millis();
    _measureFlag = false;
      pinMode(_oneLineUltrasonic_pin, OUTPUT);
      digitalWrite(_oneLineUltrasonic_pin,LOW);
      delayMicroseconds(2);
      digitalWrite(_oneLineUltrasonic_pin,HIGH);
      delayMicroseconds(10);
      digitalWrite(_oneLineUltrasonic_pin,LOW);
      pinMode(_oneLineUltrasonic_pin, INPUT);
      duration = pulseIn(_oneLineUltrasonic_pin, HIGH, timeout);
    _measureValue = duration;
  }
  else
  {
    duration = _measureValue;
  }
  return(duration);
}

double OneLineUltrasonic::distance(uint16_t MAXcm)
{
    long distance = measure(MAXcm * 55 + 200);
  if(distance == 0)
  {
    distance = MAXcm * 58;
  }
  return( (double)distance / 58.0);
}

